import React, { useState, useEffect } from 'react';
import styles from './notification.module.css';

let notificationTimeout;

export const showNotification = (message, type = 'success') => {
  const event = new CustomEvent('showNotification', {
    detail: { message, type }
  });
  window.dispatchEvent(event);
};

const Notification = () => {
  const [notification, setNotification] = useState({ show: false, type: '', message: '' });

  useEffect(() => {
    const handleNotification = (event) => {
      const { message, type } = event.detail;
      
      // 清除之前的定时器
      if (notificationTimeout) {
        clearTimeout(notificationTimeout);
      }

      setNotification({ show: true, type, message });
      
      // 3秒后自动隐藏
      notificationTimeout = setTimeout(() => {
        setNotification({ show: false, type: '', message: '' });
      }, 3000);
    };

    window.addEventListener('showNotification', handleNotification);

    return () => {
      window.removeEventListener('showNotification', handleNotification);
      if (notificationTimeout) {
        clearTimeout(notificationTimeout);
      }
    };
  }, []);

  if (!notification.show) return null;

  return (
    <div className={`${styles.notification} ${styles[notification.type]}`}>
      {notification.message}
    </div>
  );
};

export default Notification;